package com.gexin.controller.commom.WeixinTransfer;

import com.gexin.controller.commom.WeixinTransfer.model.WeixinTransferInfo;
import com.gexin.controller.commom.WeixinTransfer.model.WeixinTransferResult;
import com.gexin.model.weixin.WeixinAppConfig;
import com.google.gson.Gson;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业付款
 * @author 徐佳俊
 */
public class WeixinTransferUtil {
    private static Log log = Log.getLog(WeixinTransferUtil.class);
    private static String transfer_url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
    private static String search_url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo";

    //PathKit.getRootClassPath()+"/weixin/cer/"+
    public static WeixinTransferResult transfer(String appid, String wxkey, String mchid,
                                                String keystore_file_path, String openid,
                                                String orderId, String name,
                                                BigDecimal money, String desc) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("amount", String.valueOf(money.multiply(new BigDecimal("100")).intValue()));
        // 是否验证姓名
        // NO_CHECK：不校验真实姓名
        // FORCE_CHECK：强校验真实姓名（未实名认证的用户会校验失败，无法转账）
        // OPTION_CHECK：针对已实名认证的用户才校验真实姓名（未实名认证用户不校验，可以转账成功）
        params.put("check_name", "NO_CHECK");
        // 描述
        params.put("desc", desc);
        params.put("mch_appid", appid);
        params.put("mchid", mchid);
        // 随机字符串
        params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
        params.put("openid", openid);
        params.put("partner_trade_no", orderId);
        // 收款用户真实姓名。
        // 如果check_name设置为FORCE_CHECK或OPTION_CHECK，则必填用户真实姓名
        params.put("re_user_name", name);
        params.put("spbill_create_ip", "127.0.0.1");
        String sign = PaymentKit.createSign(params, wxkey);
        params.put("sign", sign);
        String xml = PaymentKit.toXml(params);
        System.out.println(xml);
        String xmlResult = HttpUtils.postSSL(transfer_url, xml, keystore_file_path, mchid);
        System.out.println(xmlResult);
        return toWeixinTransferResult(xmlResult);
        /*Map<String, String> resultXML = PaymentKit.xmlToMap(xmlResult.toString());
        String return_code = resultXML.get("return_code");
        String return_msg = resultXML.get("return_msg");
        ApiResponse response = new ApiResponse(true);
        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
//            renderText(return_msg);
            log.error("企业付款失败："+return_msg+",打款单号："+orderId+",打款用户："+openid+",打款金额："+money);
            response = new ApiResponse(false,"打款失败："+return_msg);
        }
        String result_code = resultXML.get("result_code");
        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
//            renderText(resultXML.get("err_code_des"));
            log.error("企业付款失败："+resultXML.get("err_code_des")+",打款单号："+orderId+",打款用户："+openid+",打款金额："+money);
            response = new ApiResponse(false,"打款失败："+resultXML.get("err_code_des"));
        }
        return response;*/
    }

    public static WeixinTransferInfo search(String appid, String wxkey, String mchid, String keystore_file_path, String orderId) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appid);
        params.put("mch_id", mchid);
        // 随机字符串
        params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
        params.put("partner_trade_no", orderId);

        String sign = PaymentKit.createSign(params, wxkey);
        params.put("sign", sign);
        String xml = PaymentKit.toXml(params);
        System.out.println(xml);
        String xmlResult = HttpUtils.postSSL(search_url, xml, keystore_file_path, mchid);
        System.out.println(xmlResult);
        return toWeixinTransferInfo(xmlResult);
        /*Map<String, String> resultXML = PaymentKit.xmlToMap(xmlResult);
        String return_code = resultXML.get("return_code");
        String return_msg = resultXML.get("return_msg");
        ApiResponse response = new ApiResponse(true);
        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
//            renderText(return_msg);
            log.error("企业付款查询失败："+return_msg+",打款单号："+orderId);
            response = new ApiResponse(false,"打款查询失败："+return_msg);
        }
        String result_code = resultXML.get("result_code");
        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
//            renderText(resultXML.get("err_code_des"));
            log.error("企业付款查询失败："+resultXML.get("err_code_des")+",打款单号："+orderId);
            response = new ApiResponse(false,"打款查询失败："+resultXML.get("err_code_des"));
        }
        return response;*/
    }

    /**
     * 企业付款返回对象
     *
     * @param xml
     * @return
     * @author xu    2018-04-04
     */
    public static WeixinTransferResult toWeixinTransferResult(String xml) {
        WeixinTransferResult wx = new WeixinTransferResult();
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            SAXBuilder builder = new SAXBuilder();

            Document document = builder.build(in);
            Element root = document.getRootElement();
            List<Element> elementList = root.getChildren();
            // 遍历节点，封装成对象
            for (Element e : elementList) {
                String name = e.getName();
                String text = e.getText();
                if ("return_code".equals(name)) {
                    wx.setReturn_code(text);
                } else if ("return_msg".equals(name)) {
                    wx.setReturn_msg(text);
                } else if ("result_code".equals(name)) {
                    wx.setResult_code(text);
                } else if ("mch_appid".equals(name)) {
                    wx.setMch_appid(text);
                } else if ("mchid".equals(name)) {
                    wx.setMchid(text);
                } else if ("device_info".equals(name)) {
                    wx.setDevice_info(text);
                } else if ("nonce_str".equals(name)) {
                    wx.setNonce_str(text);
                } else if ("partner_trade_no".equals(name)) {
                    wx.setPartner_trade_no(text);
                } else if ("payment_no".equals(name)) {
                    wx.setPayment_no(text);
                } else if ("payment_time".equals(name)) {
                    wx.setPayment_time(text);
                } else if ("err_code".equals(name)) {
                    wx.setErr_code(text);
                } else if ("err_code_des".equals(name)) {
                    wx.setErr_code_des(text);
                }
            }

            //	System.out.println(msgReq.getFromUserName());
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return wx;
    }

    /**
     * 查询企业付款接口返回对象
     *
     * @param xml
     * @return
     * @author xu    2019-01-15
     */
    public static WeixinTransferInfo toWeixinTransferInfo(String xml) {
        WeixinTransferInfo wx = new WeixinTransferInfo();
        InputStream in = null;
        try {
            in = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            SAXBuilder builder = new SAXBuilder();

            Document document = builder.build(in);
            Element root = document.getRootElement();
            List<Element> elementList = root.getChildren();
            // 遍历节点，封装成对象
            for (Element e : elementList) {
                String name = e.getName();
                String text = e.getText();
                if ("return_code".equals(name)) {
                    wx.setReturn_code(text);
                } else if ("return_msg".equals(name)) {
                    wx.setReturn_msg(text);
                } else if ("result_code".equals(name)) {
                    wx.setResult_code(text);
                } else if ("err_code".equals(name)) {
                    wx.setErr_code(text);
                } else if ("err_code_des".equals(name)) {
                    wx.setErr_code_des(text);
                } else if ("appid".equals(name)) {
                    wx.setAppid(text);
                } else if ("mch_id".equals(name)) {
                    wx.setMch_id(text);
                } else if ("nonce_str".equals(name)) {
                    wx.setNonce_str(text);
                } else if ("partner_trade_no".equals(name)) {
                    wx.setPartner_trade_no(text);
                } else if ("payment_time".equals(name)) {
                    wx.setPayment_time(text);
                } else if ("detail_id".equals(name)) {
                    wx.setDetail_id(text);
                } else if ("status".equals(name)) {
                    wx.setStatus(text);
                } else if ("reason".equals(name)) {
                    wx.setReason(text);
                } else if ("openid".equals(name)) {
                    wx.setOpenid(text);
                } else if ("transfer_name".equals(name)) {
                    wx.setTransfer_name(text);
                } else if ("payment_amount".equals(name)) {
                    wx.setPayment_amount(text);
                } else if ("transfer_time".equals(name)) {
                    wx.setTransfer_time(text);
                } else if ("desc".equals(name)) {
                    wx.setDesc(text);
                }
            }

            //	System.out.println(msgReq.getFromUserName());
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return wx;
    }

}

    /**
     * 获取用户openID
     * @Author  科帮网
     * @param code
     * @return  String
     * @Date    2017年7月31日
     * 更新日志
     * 2017年7月31日  科帮网 首次创建
     *
     */
//          weixinAppConfig.getAppId(),
//                  weixinAppConfig.getWxKey(),
//                  weixinAppConfig.getWxMchid(),
//                  weixinAppConfig.getKeystoreFilePath(),
//                  authUser.getOpenid(),
//                  userRebate.getId(),
//                  authUser.getNickname(),
//                  userRebate.getPrice(),
//                  "商品返现");
//    public static String getOpenId(String code){
//        WeixinAppConfig weixinAppConfig = WeixinAppConfig.dao.findById(2);
//        if (code != null) {
//            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
//                    + "appid="+ weixinAppConfig.getAppId()+"&"
//                    + "&secret="+ weixinAppConfig.getAppSecret() + "&code="
//                    +code + "&grant_type=authorization_code";
//            HttpUtils.get(url);
//            String returnData = getReturnData(url);
//            Gson gson = new Gson();
//            OpenIdClass openIdClass = gson.fromJson(returnData,
//                    OpenIdClass.class);
//            if (openIdClass.getOpenid() != null) {
//                return openIdClass.getOpenid();
//            }
//        }
//        return "**************";
//    }

